package com.wang.validator;

import com.wang.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * @Classname UserValidator
 * @Description TODO
 * @Date 2024/5/21 9:48
 * @Created by pc
 */
@Component
public class UserValidator implements Validator {
    // 校验类型
    @Override
    public boolean supports(Class<?> clazz) {
        System.out.println(clazz);
        // 校验传递的类型是否合法
        return User.class.isAssignableFrom(clazz);
    }

    // 校验值
    @Override
    public void validate(Object target, Errors errors) {
        User user = (User)target;
        // 校验字段
        ValidationUtils.rejectIfEmptyOrWhitespace(errors,"name","","用户名为空");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors,"password","","密码为空");
        if(user.getName().length() < 5){
            errors.rejectValue("name","","用户名长度小于5");
        }
    }
}
